package com.zhang.network.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zhang.network.mapper.FriendMapper;
import com.zhang.network.model.Friend;
import com.zhang.network.model.Network;
import com.zhang.network.model.User;
import com.zhang.network.mapper.UserMapper;
import com.zhang.network.model.user.UserQueryDTO;
import com.zhang.network.service.UserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zhang.util.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author zhang
 * @since 2021-04-03
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Resource
    FriendMapper friendMapper;

    @Override
    public Page<User> pageUser(UserQueryDTO queryDTO) {
        Page<User> page = new Page<>(queryDTO.getPageNum(), queryDTO.getPageSize());
        QueryWrapper<User> userWrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(queryDTO.getNickName())) {
            userWrapper.like("nick_name", queryDTO.getNickName());
        }
        if (StringUtils.isNotBlank(queryDTO.getAccount())) {
            userWrapper.like("account", queryDTO.getAccount());
        }
        return baseMapper.selectPage(page, userWrapper);
    }

    @Override
    public Page<User> pageNoFriendUser(UserQueryDTO queryDTO) {
        QueryWrapper<Friend> wrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(queryDTO.getId())) {
            wrapper.eq("user_id", queryDTO.getId());
        }
        List<Friend> allFriends = friendMapper.selectList(wrapper);

        Page<User> page = new Page<>(queryDTO.getPageNum(), queryDTO.getPageSize());
        List<Integer> list = allFriends.stream().map(friend -> friend.getFriendId()).collect(Collectors.toList());

        QueryWrapper<User> userWrapper = new QueryWrapper<>();
        userWrapper.notIn("id", queryDTO.getId());
        if (list.size() > 0) {
            userWrapper.notIn("id", list);
        }
        if (StringUtils.isNotBlank(queryDTO.getNickName())) {
            userWrapper.like("nick_name", queryDTO.getNickName());
        }
        if (StringUtils.isNotBlank(queryDTO.getAccount())) {
            userWrapper.like("account", queryDTO.getAccount());
        }
        return baseMapper.selectPage(page, userWrapper);
    }

    @Override
    public boolean insertUser(User user) {
        return baseMapper.insert(user) != 0;
    }

    @Override
    public boolean modifyUser(User user) {
        return baseMapper.updateById(user) != 0;
    }

    @Override
    public boolean deleteUser(Integer id) {
        return baseMapper.deleteById(id) != 0;
    }
}
